<template>
    <div>
        <div class="search-term">
            <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
                <el-form-item>
                    <el-input
                            placeholder="请输入名师名称"
                            v-model="searchInfo.teacherName"
                            clearable
                            size="small"
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select
                            v-model="searchInfo.status"
                            placeholder="请选择状态"
                            clearable
                            size="small"
                    >
                        <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSubmit" type="primary" size="mini"
                    >搜 索
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="openDialog('add')" size="mini">新增</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table :data="tableData" style="width: 100%;margin-bottom: 10px;" border>
            <el-table-column prop="teacherName" label="名师名称" align="center">
            </el-table-column>
            <el-table-column prop="sortBy" label="排序" align="center">
            </el-table-column>
            <el-table-column prop="updateTime" label="上架时间" align="center">
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
                <template slot-scope="scope">
                    <span :class="scope.row.status === 1 ? 'green' : 'red'">{{scope.row.status === 1 ? "上架" : "下架"}}</span>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="350px">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="info"
                            icon="el-icon-view"
                            @click="viewTopTeacher(scope.row.teacherId)"
                    >查看
                    </el-button>
                    <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                            @click="editTopTeacher(scope.row.teacherId)"
                    >编辑
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            @click="deleteTopTeacher(scope.row.teacherId)"
                    >删除
                    </el-button>
                    <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-caret-top"
                            v-if="scope.row.status===0"
                            @click="updateTopTeacherStatus(scope.row.teacherId,1)"
                    >上架
                    </el-button>
                    <el-button
                            size="mini"
                            type="warning"
                            icon="el-icon-caret-bottom"
                            v-if="scope.row.status===1"
                            @click="updateTopTeacherStatus(scope.row.teacherId,0)"
                    >下架
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page="currPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100]"
                :style="{ float: 'right', padding: '20px' }"
                :total="totalCount"
                @current-change="handlepageChange"
                @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>

        <!--对话框-->
        <el-dialog
                :before-close="closeDialog"
                :title="dialogTitle"
                :visible.sync="dialogFormVisible"
                class="dialogs"
        >
            <el-form
                    :model="form"
                    :inline="true"
                    :rules="rules"
                    label-width="80px"
                    ref="topTeacherForm"
            >
                <el-form-item label="名师照片" prop="teacherImg" class="pics">
                    <el-upload
                            :disabled="type==='view'"
                            class="avatar-uploader"
                            :action="`${path}/api-system/file/upload/top-teacher`"
                            list-type="picture-card"
                            :show-file-list="false"
                            :before-upload="checkFile"
                            :headers="{ Authorization: token }"
                            :on-error="uploadError"
                            :on-success="uploadSuccess"
                    >
                        <div class="header-background">
                            <img v-if="isShowImg" :src="form.teacherImg" class="avatar" width="100%" height="100%"/>
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="教师名称" prop="teacherName" style="margin-right: 120px">
                    <el-input
                            :disabled="type==='view'"
                            autocomplete="off"
                            v-model="form.teacherName"
                            size="small"
                            placeholder="请输入教师名称"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sortBy" style="width: 510px">
                    <el-input-number
                            :disabled="type==='view'"
                            v-model="form.sortBy"
                            :min="1"
                            :max="100"
                            size="small"
                            style=""
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="擅长课程" prop="skillCourse" style="margin-right: 120px">
                    <el-input
                            :disabled="type==='view'"
                            autocomplete="off"
                            v-model="form.skillCourse"
                            size="small"
                            placeholder="请输入擅长课程"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="名师介绍">
                    <el-input type="textarea" :disabled="type==='view'" v-model="form.introduce"></el-input>
                </el-form-item>
                <el-form-item label="名师风采" prop="introduceImgList" style=" width:900px">
                    <!--编辑情况-->
                    <el-upload
                            v-if="type!=='view'"
                            :on-remove="(file, fileList) => handleRemove(file, fileList)"
                            :before-upload="checkFile"
                            :action="`${path}/api-system/file/upload/top-teacher`"
                            list-type="picture-card"
                            :headers="{ Authorization: token,clientType: 'webApp' }"
                            :on-error="uploadError"
                            :file-list="introduceImgList"
                            :on-success="(response, file, fileList) => introduceImgUploadSuccess(response, file, fileList)">
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <el-upload
                            v-else-if="introduceImgList.length===0"
                            :disabled="true"
                            :action="`${path}/api-system/file/upload/top-teacher`"
                            class="avatar-uploader"
                            list-type="picture-card">
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-else>
                        <img v-for="item in introduceImgList" :src="item.url" class="avatar"
                             style="width: 148px;height:148px;margin-right: 10px;"/>
                    </div>
                    <!--查看有数据情况-->
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeDialog" size="mini">取 消</el-button>
                <el-button @click="enterDialog" type="primary" size="mini">确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    // 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索
    import {mapGetters} from "vuex";
    import {
        topTeacherList,
        addTopTeacher,
        updateTopTeacher,
        getTopTeacher,
        deleteTopTeacher,
        updateTopTeacherStatus
    } from "@/api/topTeacher";
    import infoList from "@/components/mixins/infoList";

    export default {
        name: "topTeacher",
        mixins: [infoList],
        data() {
            return {
                isShowImg: false,
                path: process.env.VUE_APP_BASE_API,
                type: "",
                dialogTitle: "",
                dialogFormVisible: false,
                searchInfo: {},
                listApi: topTeacherList,
                rules: {
                    teacherName: [{required: true, message: "请输入名师名称", trigger: "blur"},],
                    teacherImg: [{required: true, message: "请上传照片", trigger: "blur"}],
                    sortBy: [{required: true, message: "请输入序号", trigger: "blur"}],
                },
                form: {sortBy: 1},
                introduceImgList: [],
                statusOptions: [{
                    value: 0,
                    label: "下架",
                }, {
                    value: 1,
                    label: "上架",
                }],
            }
        },
        computed: {
            ...mapGetters("user", ["userInfo", "token"]),
        },
        methods: {
            //条件搜索前端看此方法
            onSubmit() {
                this.page = 1;
                this.pageSize = 10;
                this.getTableData();
            },
            //初始化表单
            initForm() {
                this.introduceImgList = [];
                this.$refs.topTeacherForm.resetFields();
            },
            //查看名师
            async viewTopTeacher(teacherId) {
                const res = await getTopTeacher(teacherId);
                this.form = res.data;
                if (this.form.teacherImg !== '') {
                    this.isShowImg = true;
                }
                let imageList = this.form.imageList;
                if (imageList) {
                    imageList.forEach((item) => {
                        this.introduceImgList.push({url: item});
                    })
                }
                this.openDialog("view");
            },
            //编辑名师
            async editTopTeacher(teacherId) {
                const res = await getTopTeacher(teacherId);
                this.form = res.data;
                if (this.form.teacherImg !== '') {
                    this.isShowImg = true;
                }
                let imageList = this.form.imageList;
                if (imageList) {
                    imageList.forEach((item) => {
                        this.introduceImgList.push({url: item});
                    })
                }
                this.openDialog("edit");
            },
            //弹出对话框
            openDialog(type) {
                switch (type) {
                    case "add":
                        this.dialogTitle = "新增名师";
                        this.form={sortBy: 1};
                        this.isShowImg = false;
                        break;
                    case "edit":
                        this.dialogTitle = "编辑名师";
                        break;
                    case "view":
                        this.dialogTitle = "查看名师";
                        break;
                    default:
                        break;
                }
                this.type = type;
                this.dialogFormVisible = true;
            },
            //关闭对话框
            closeDialog() {
                this.initForm();
                this.dialogFormVisible = false;
            },
            //文件上传
            checkFile(file) {
                this.fullscreenLoading = true;
                const isJPG = file.type === "image/jpeg";
                const isPng = file.type === "image/png";
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG && !isPng) {
                    this.$message.error("上传头像图片只能是 JPG或png 格式!");
                    this.fullscreenLoading = false;
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                    this.fullscreenLoading = false;
                }
                return (isPng || isJPG) && isLt2M;
            },
            uploadError() {
                this.$message({
                    type: "error",
                    message: "上传失败",
                });
                this.fullscreenLoading = false;
            },
            uploadSuccess(res) {
                this.fullscreenLoading = false;
                if (res.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "上传成功",
                    });
                    this.isShowImg = true;
                    this.form.teacherImg = res.data;
                } else {
                    this.$message({
                        type: "warning",
                        message: res.msg,
                    });
                }
            },
            //删除名师
            async deleteTopTeacher(activityId) {
                this.$confirm("此操作将永久删除该名师, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(async () => {
                    const res = await deleteTopTeacher(activityId);
                    if (res.statusCode === 0) {
                        this.$message({
                            type: "success",
                            message: "删除成功",
                            showClose: true,
                        });
                        this.getTableData();
                    }
                })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            },
            //上架/下架
            async updateTopTeacherStatus(activityId, status) {
                this.$confirm("此操作将上架/下架该名师, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(async () => {
                    const res = await updateTopTeacherStatus(activityId, status);
                    if (res.statusCode === 0) {
                        this.$message({
                            type: "success",
                            message: "修改成功",
                            showClose: true,
                        });
                        this.getTableData();
                    }
                })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            },
            //保存/修改
            async enterDialog() {
                this.$refs.topTeacherForm.validate(async (valid) => {
                    if (valid) {
                        switch (this.type) {
                            case "add": {
                                const res = await addTopTeacher(this.form);
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "添加成功",
                                        showClose: true,
                                    });
                                    this.getTableData();
                                    this.closeDialog();
                                }
                            }
                                break;
                            case "edit": {
                                const res = await updateTopTeacher(this.form);
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "编辑成功",
                                        showClose: true,
                                    });
                                    this.getTableData();
                                    this.closeDialog();
                                }
                            }
                                break;
                            default: {
                                this.$message({
                                    type: "error",
                                    message: "未知操作",
                                    showClose: true,
                                });
                            }
                                break;
                        }
                    }
                });
            },
            //多图片
            handleRemove(file, fileList) {
                let imagArray = [];
                if (fileList.length > 0) {
                    fileList.forEach(function (value) {
                        let url = value.response === undefined ? value.url : value.response.data;
                        imagArray.push(url);
                    });
                }
                this.form.imageList = imagArray;
            },
            introduceImgUploadSuccess(response) {
                if (response.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "上传成功",
                    });
                    if (this.form.imageList === undefined) {
                        this.form.imageList = [];
                    }
                    this.form.imageList.push(response.data);
                }
            },
        },
        async created() {
            this.getTableData();
            this.btns = this.$route.meta.btnList;

        },
    };
</script>
<style scoped lang="scss">
    .green {
        color: #67c23a;
    }

    .red {
        color: #f56c6c;
    }

    .button-box {
        // padding: 10px 20px;
        .el-button {
            float: right;
        }
    }

    .el-tag--mini {
        margin-left: 5px;
    }

    .dialogs {
        ::v-deep .el-dialog {
            width: 40%;
        }

        ::v-deep .el-input-group--append .el-input__inner {
            width: 170px !important;
        }

        ::v-deep .el-dialog__body {
            padding: 15px 20px 10px 20px;
        }

        /*::v-deep .el-input__inner {*/
        /*    width: 225px;*/
        /*}*/

        ::v-deep .el-textarea__inner {
            width: 450px;
        }

        .dialog-footer {
            text-align: center;
        }

        ::v-deep .el-input-number .el-input__inner {
            width: 130px;
        }

        ::v-deep .el-form .pics {
            width: 100%;
            margin-bottom: 22px;
        }

        ::v-deep .el-form .el-divider .el-divider__text {
            font-weight: bold;
            color: #409eff;
        }

        .item-label {
            ::v-deep .el-form-item__label {
                width: 110px !important;
            }

            ::v-deep .el-input__inner {
                width: 162px;
            }
        }
    }

    .header-background {
        position: absolute;
        width: 146px;
        height: 146px;
    }
</style>
